package com.company.array;

import java.util.Arrays;

/**
 * @author jrue
 * @description https://leetcode-cn.com/problems/longest-consecutive-sequence/
 * 给定一个未排序的整数数组，找出最长连续序列的长度。
 * 要求算法的时间复杂度为 O(n)。
 * @date 2019/11/14 11:27
 */
public class LongestConsecutive {

    public static void main(String[] args) {
        System.out.println(longestConsecutive(new int[]{1,2,0,1}));
    }

    public static int longestConsecutive(int[] nums) {
        if (nums.length == 0) return 0;
        Arrays.sort(nums);
        int maxLength = 0;
        int length  = 0;
        for (int i = 1; i < nums.length; i++) {
            if (nums[i] == nums[i -1 ]){

            }
            else if (nums[i] - 1 == nums[i -1]) {
                length++;
            } else {
                if (length > maxLength) maxLength = length;
                length = 0;

            }
        }
        if (maxLength < length) {
            maxLength = length;
        }
        return maxLength + 1;
    }

}
